package site.xuqing.autohelperengine.util;

import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;

import site.xuqing.autohelperengine.permission.FloatWindowPermissionChecker;
import site.xuqing.autohelperengine.ui.AuthorityActivity;

public class AuthorityUtil {
    private static final String ACCESSIBILITY_SERVICES_PACKAGE="site.xuqing.autohelperengine.service.HelperService";
    public static boolean hasAuthority(Context context) {
        return hasOverlayPermission(context) && isServiceRunning(context);
    }

    public static boolean hasOverlayPermission(Context context) {
        return FloatWindowPermissionChecker.checkFloatWindowPermission(context.getApplicationContext());
    }

    public static boolean isServiceRunning(Context context) {
        int accessibilityEnabled = 0;
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(
                    context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
                splitter.setString(settingValue);
                while (splitter.hasNext()) {
                    String accessabilityService = splitter.next();
                    if (accessabilityService.equalsIgnoreCase(context.getPackageName()+"/"+ACCESSIBILITY_SERVICES_PACKAGE)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    public static void goAuthorityActivity(Context context) {
        goAuthorityActivity(context,true,true);
    }

    public static void goAuthorityActivity(Context context,boolean isNeedOverlayPermission,boolean isNeedAccessibilityPermission) {
        AuthorityActivity.startActivity(context,isNeedOverlayPermission,isNeedAccessibilityPermission);
    }
}
